"use client";

import { useState, useEffect } from "react";
import CarCard from "@/components/CarCard";
import CarSearch from "@/components/CarSearch";
import { CarSearchParams, carApiService } from "@/services/api";
import { Car } from "@/data/cars";
import '@ant-design/v5-patch-for-react-19';

export default function CarsPage() {
  const [cars, setCars] = useState<Car[]>([]);
  const [loading, setLoading] = useState(true);
  const [loadingMore, setLoadingMore] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);
  const [hasMore, setHasMore] = useState(true);
  const [activeTab, setActiveTab] = useState<'all' | 'new' | 'used'>('all');
  const [stats, setStats] = useState({
    totalCars: 0,
    newCars: 0,
    usedCars: 0,
    brandsCount: 0,
    avgPrice: 0,
  });

  useEffect(() => {
    loadInitialData();
  }, []);

  const loadInitialData = async () => {
    try {
      setLoading(true);
      const [carsResponse, statsResponse] = await Promise.all([
        carApiService.searchCars({ page: 1, pageSize: 10 }),
        carApiService.getStats(),
      ]);

      if (carsResponse.code === 200) {
        setCars(carsResponse.data.cars);
        setHasMore(carsResponse.data.cars.length === 10);
      }

      if (statsResponse.code === 200) {
        setStats(statsResponse.data);
      }
    } catch (error) {
      console.error("加载数据失败:", error);
    } finally {
      setLoading(false);
    }
  };

  const loadMoreCars = async () => {
    if (loadingMore || !hasMore) return;
    
    try {
      setLoadingMore(true);
      const nextPage = currentPage + 1;
      const response = await carApiService.searchCars({ 
        page: nextPage, 
        pageSize: 10,
        carType: activeTab === 'all' ? undefined : activeTab
      });

      if (response.code === 200) {
        setCars(prev => [...prev, ...response.data.cars]);
        setCurrentPage(nextPage);
        setHasMore(response.data.cars.length === 10);
      }
    } catch (error) {
      console.error("加载更多失败:", error);
    } finally {
      setLoadingMore(false);
    }
  };

  const handleTabChange = async (tab: 'all' | 'new' | 'used') => {
    setActiveTab(tab);
    setLoading(true);
    setCurrentPage(1);
    
    try {
      const response = await carApiService.searchCars({ 
        page: 1, 
        pageSize: 10,
        carType: tab === 'all' ? undefined : tab
      });

      if (response.code === 200) {
        setCars(response.data.cars);
        setHasMore(response.data.cars.length === 10);
      }
    } catch (error) {
      console.error("切换分类失败:", error);
    } finally {
      setLoading(false);
    }
  };

  const handleSearch = async (searchParams: CarSearchParams) => {
    try {
      setLoading(true);
      const response = await carApiService.searchCars({
        ...searchParams,
        page: 1,
        pageSize: 10,
        carType: activeTab === 'all' ? undefined : activeTab
      });

      if (response.code === 200) {
        setCars(response.data.cars);
        setCurrentPage(1);
        setHasMore(response.data.cars.length === 10);
      }
    } catch (error) {
      console.error("搜索失败:", error);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 to-gray-100">
      {/* 头部区域 */}
      <div className="bg-[linear-gradient(to_right,#EC302F,#F26E6D)] text-white">
        <div className="max-w-7xl mx-auto px-4 py-8">
          <div className="text-center">
            <h1 className="text-4xl md:text-5xl font-bold mb-4">全部车辆展示</h1>
            <p className="text-xl mb-8 max-w-4xl mx-auto opacity-80">
              浏览我们完整的汽车库存，包含新车和二手车
            </p>
          </div>
          
          {/* 搜索区域 */}
          <div className="max-w-7xl mx-auto px-4">
            <div className="flex justify-center mb-8">
              <div className="w-full max-w-4xl">
                <CarSearch onSearch={handleSearch} />
              </div>
            </div>
          </div>
        </div>
      </div>

      <div className="max-w-7xl mx-auto px-4 py-8">
        {/* 加载状态 */}
        {loading && (
          <div className="text-center py-12">
            <div className="inline-block animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"></div>
            <p className="mt-4 text-gray-600">正在加载车辆数据...</p>
          </div>
        )}

        {/* 车辆列表 */}
        {!loading && (
          <>
            {/* Tabs分类 */}
            <div className="flex justify-center mb-8">
              <div className="bg-white rounded-full p-1 shadow-lg">
                <div className="flex space-x-1">
                  <button
                    onClick={() => handleTabChange('all')}
                    className={`px-6 py-2 rounded-full text-sm font-medium transition-all duration-200 ${
                      activeTab === 'all'
                        ? 'bg-blue-600 text-white shadow-md'
                        : 'text-gray-600 hover:text-blue-600 hover:bg-gray-100'
                    }`}
                  >
                    全部 ({stats.totalCars})
                  </button>
                  <button
                    onClick={() => handleTabChange('new')}
                    className={`px-6 py-2 rounded-full text-sm font-medium transition-all duration-200 ${
                      activeTab === 'new'
                        ? 'bg-green-600 text-white shadow-md'
                        : 'text-gray-600 hover:text-green-600 hover:bg-gray-100'
                    }`}
                  >
                    新车 ({stats.newCars})
                  </button>
                  <button
                    onClick={() => handleTabChange('used')}
                    className={`px-6 py-2 rounded-full text-sm font-medium transition-all duration-200 ${
                      activeTab === 'used'
                        ? 'bg-orange-600 text-white shadow-md'
                        : 'text-gray-600 hover:text-orange-600 hover:bg-gray-100'
                    }`}
                  >
                    二手车 ({stats.usedCars})
                  </button>
                </div>
              </div>
            </div>

            {cars.length === 0 ? (
              <div className="text-center py-16 bg-white rounded-2xl shadow-lg">
                <div className="text-8xl mb-6">🚗</div>
                <h4 className="text-2xl font-semibold text-gray-900 mb-4">
                  暂无匹配车辆
                </h4>
                <p className="text-gray-600 text-lg">
                  请尝试调整筛选条件或搜索其他关键词
                </p>
              </div>
            ) : (
              <>
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-5 gap-4">
                  {cars.map((car) => (
                    <CarCard key={car.id} car={car} />
                  ))}
                </div>
                
                {/* 加载更多按钮 */}
                {hasMore && (
                  <div className="text-center mt-8">
                    <button
                      onClick={loadMoreCars}
                      disabled={loadingMore}
                      className="bg-blue-600 text-white px-8 py-3 rounded-full font-medium hover:bg-blue-700 transition-colors duration-200 disabled:opacity-50 disabled:cursor-not-allowed"
                    >
                      {loadingMore ? (
                        <span className="flex items-center">
                          <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2"></div>
                          加载中...
                        </span>
                      ) : (
                        '加载更多'
                      )}
                    </button>
                  </div>
                )}
              </>
            )}
          </>
        )}
      </div>
    </div>
  );
}